package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(Message message,
                         OrderEntity orderEntity,
                         Channel channel) throws IOException {
        // todo 消息是否是第二次及以后发送过来的
        Boolean redelivered = message.getMessageProperties().getRedelivered();
        System.out.println("收到过期的订单信息，准备关闭订单: " + orderEntity.getOrderSn());
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            orderService.closeOrder(orderEntity);
            // todo 手动调用支付宝的收单功能，避免时延或者订单过期未付款，导致订单被关闭，库存解锁了
            // todo 但是支付成功了的问题
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            e.printStackTrace();
            // 执行异常，拒绝消息
            channel.basicReject(deliveryTag, true);
        }

    }
}
